package com.fansm.controller;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorController {

    public static void main(String[] args) {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
        //2秒后执行runnable任务
        scheduledThreadPoolExecutor.schedule(() -> {
            System.out.println("This is runable1 task");
        }, 2, TimeUnit.SECONDS);

        //提交一个2秒后才执行的runnable任务
        //既然runnable无法返回结果,为什么还要有Future呢,因为我们可以通过Future进行取消任务等操作
        ScheduledFuture<?> runnableFuture = scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {
            System.out.println("This is runable2 task");
        }, 1,2, TimeUnit.SECONDS);
        //取消任务
//        runnableFuture.cancel(true);

        //休眠3秒,确保上面的任务都被执行完
        mySleep(3);
        System.out.println("========================");

        BlockingQueue<Runnable> queue = scheduledThreadPoolExecutor.getQueue();
        System.out.println(queue.size());

//        scheduledThreadPoolExecutor.shutdown();

    }

    private static void mySleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
